package com.acmen.ump.core.handler;

import com.acmen.ump.core.jwt.JwtUtil;
import com.acmen.ump.entity.sys.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Acmen
 * @ClassName ResponseBodyAdviceHandler.java
 * @Description  对com.acmen.ump.adminapi.controller包下的返回对象进行统一处理
 * @CreateTime 2019年08月26日 15:38:04
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.acmen.ump.adminapi.controller"})
public class ResponseBodyAdviceHandler implements ResponseBodyAdvice {
    /**
     * 判断支持的类型
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
    }

    /**
     * 对结果进行封装，如果已经封装为ApiResponse对象，则不作处理，包装为ApiResponse对象
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {



        /**
         * 刷新token
         */
        ServletServerHttpResponse ssResp = (ServletServerHttpResponse)response;
        HttpServletResponse resp = ssResp.getServletResponse();
        SysUser user = new SysUser();
        user.setAccount("email");
        try {
            resp.setHeader("Authorization", JwtUtil.generateToken(user,30));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return body;
    }
}
